/*
Copyright 2021 LuJun

Permission is hereby granted, free of charge, to any person obtaining a copy 
of this software and associated documentation files (the "Software"), to deal 
in the Software without restriction, including without limitation the rights 
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
copies of the Software, and to permit persons to whom the Software is furnished 
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in 
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

import { Node, Prefab, instantiate, director, game } from 'cc';
import { PrefabBase } from './prefab-base';
import { indexMgr } from '../index/index';
import { nodePools } from '../preset/node-pools';
import { Macro, request } from '../core';

const TAG = 'lcc/prefab/prefab-manager.ts';

/**
 * @zh
 * 预制体实例
 */
const PREFAB_INSTANCE = 'lcc_Prefab';

/**
 * @zh
 * 预制体配置
 */
interface PrefabConfig {
    /**
     * @zh
     * 预制体文件
     */
    file: string;

    /**
     * @zh
     * 池中分配
     */
    pool?: boolean;
}

/**
 * @zh
 * 预制体数据
 */
interface PrefabData {
    /**
     * @zh
     * 预制体
     */
    prefab: Prefab;

    /**
     * @zh
     * 配置
     */
    config: PrefabConfig;

    /**
     * @zh
     * 预加载
     */
    preload?: boolean;
}

/**
 * @zh
 * 预制体管理器
 */
class PrefabManager {
    /**
     * @zh
     * 单例对象
     */
    private static _instance: PrefabManager = null!;

    /**
     * @zh
     * 获得单例对象
     */
    static get instance() {
        if (PrefabManager._instance === null) {
            PrefabManager._instance = new PrefabManager();
        }
        return PrefabManager._instance;
    }

    /**
     * @zh
     * 构造函数
     */
    private constructor() {}

    /**
     * @zh
     * 预制体数据表
     */
    private _prefabDatas: { [key: string]: PrefabData } = Object.create(null);

    /**
     * @zh
     * 预制体实例，用于在预制体上挂配置
     */
    private _prefabInstances: { [key: string]: PrefabBase } = Object.create(null);

    /**
     * @zh
     * 预制体实例节点
     */
    private _instanceRoot: Node = null!;

    /**
     * @zh
     * 释放预制体
     *
     * @param pname - 预制体名称
     * @param preload - 预加载也释放
     */
    releasePrefabConfig(pname: string, preload: boolean = false) {
        let prefabconf = this._prefabDatas[pname];
        if (prefabconf && (!prefabconf.preload || preload)) {
            prefabconf.prefab.decRef();
            delete this._prefabDatas[pname];
            nodePools.clearPool(pname);
        }
    }

    /**
     * @zh
     * 释放预制体数组
     *
     * @param pnames - 预制体数组
     * @param preload - 预加载也释放
     */
    releasePrefabConfigs(pnames: string[], preload: boolean = false) {
        for (let pname of pnames) {
            this.releasePrefabConfig(pname, preload);
        }
    }

    /**
     * @zh
     * 预加载预制体
     *
     * @param pname - 预制体名称
     */
    async preloadPrefabConfig(pname: string) {
        let prefabconf = await this.getPrefabData(pname);
        if (prefabconf) {
            prefabconf.preload = true;
        }
    }

    /**
     * @zh
     * 预加载预制体数组
     *
     * @param pnames - 预制体数组
     * @param progress - 进度
     */
    async preloadPrefabConfigs(pnames: string[], progress = (p: number) => {}) {
        for (let i = 0, len = pnames.length; i < len; i++) {
            await this.preloadPrefabConfig(pnames[i]);
            progress((i + 1) / len);
        }
    }

    /**
     * @zh
     * 获得预制体数据
     *
     * @param pname 预制体名称
     */
    private async getPrefabData(pname: string) {
        let prefabData = this._prefabDatas[pname];
        if (!prefabData) {
            let config = indexMgr.getIndex<PrefabConfig>(Macro.INDEXPATH_PREFAB + '/' + pname);
            if (config) {
                let prefab = await request.get<Prefab>(config.file, { subproto: 'prefab' });
                prefabData = {
                    prefab: prefab,
                    config: config
                };
                prefab.addRef();
                this._prefabDatas[pname] = prefabData;
            }
        }
        return prefabData;
    }

    /**
     * @zh
     * 创建预制体
     *
     * @param pname - 预制体名称
     * @param pool - 在池中创建
     */
    async createPrefab<T extends PrefabBase>(pname: string, pool?: boolean) {
        let prefabconf = await this.getPrefabData(pname);
        if (prefabconf) {
            let _pool = pool || prefabconf.config.pool;
            let node: Node = null!;
            if (_pool) {
                node = nodePools.getNode(prefabconf.prefab, pname);
            } else {
                node = instantiate(prefabconf.prefab);
            }
            let prefab = node.getComponent(PrefabBase) || node.getComponentInChildren(PrefabBase);
            if (!prefab) {
                prefab = node.addComponent(PrefabBase);
            }
            prefab._setRootNode(node);
            prefab._setPrefabName(pname);
            return prefab as T;
        }
    }

    /**
     * @zh
     * 释放预制体到池中
     *
     * @param prefab - 预制体对象
     * @param pool - 在池中创建
     */
    releasePrefab(prefab: PrefabBase, pool?: boolean) {
        let pname = prefab.getPrefabName();
        let _pool = pool;
        if (!_pool) {
            let prefabconf = this._prefabDatas[pname];
            if (prefabconf) {
                _pool = prefabconf.config.pool;
            }
        }
        if (_pool) {
            nodePools.putNode(prefab.getRootNode());
        } else {
            prefab.getRootNode().destroy();
        }
    }

    /**
     * @zh
     * 获得预制体实例，一般用于获得在预制体上放的配置
     *
     * @param pname - 预制体名称
     */
    async getPrefabInstance<T extends PrefabBase>(pname: string) {
        let prefab = this._prefabInstances[pname];
        if (!prefab) {
            prefab = (await this.createPrefab(pname))!;
            if (!this._instanceRoot) {
                this._instanceRoot = new Node(PREFAB_INSTANCE);
                director.getScene()!.addChild(this._instanceRoot);
                game.addPersistRootNode(this._instanceRoot);
            }
            prefab.getRootNode().parent = this._instanceRoot;
            this._prefabInstances[pname] = prefab;
        }
        return prefab as T;
    }

    /**
     * @zh
     * 释放预制体实例，一般用于释放在预制体上放的配置
     *
     * @param pname - 预制体名称
     */
    releasePrefabInstance(pname: string) {
        let prefab = this._prefabInstances[pname];
        if (prefab) {
            this.releasePrefab(prefab);
            delete this._prefabInstances[pname];
        }
    }
}

/**
 * @zh
 * 预制体管理器对象
 */
export const prefabMgr = PrefabManager.instance;
